package com.lz.gmall.exception;

import com.alibaba.fastjson.JSON;
import com.lz.gmall.common.execption.GmallException;
import com.lz.gmall.common.result.Result;
import com.lz.gmall.common.result.ResultCodeEnum;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//全局异常处理类
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = GmallException.class)
    public Result gmallException(GmallException e){
        e.printStackTrace();
        ResultCodeEnum resultCodeEnum = e.getResultCodeEnum();
        return Result.build(null,resultCodeEnum);
    }

    @ExceptionHandler(value = Exception.class)
    public Result exception(Exception e){
        e.printStackTrace();
        return Result.build(null,ResultCodeEnum.SYSTEM_ERROR);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();

        Map<String,String> map = new HashMap<>();

        //这是校验不通过，所提供的方法
        BindingResult bindingResult = e.getBindingResult();
        //错误的所有字段
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            //获取到错误字段
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();

            String value = map.get(field);
            //一个字段出现多个错误，同时展现
            if (StringUtils.isEmpty(value)){
                //没有出现相同字段的错误信息
                map.put(field,message);
            }else {
                //出现相同字段的错误信息,将两个错误信息一起拼接
                map.put(field,value+","+message);
            }
        }

        Result result = new Result();
        result.setCode(8990);
        result.setMessage(JSON.toJSONString(map));
        return result;
    }
}
